/*
 * Created by Federico Pisarello - SisDev Software (c) 2012 - fpisarello@sisdevsoft.com
 */

var popForm = 'usuariosPop.php';
var actionForm = 'usuariosAction.php';

var joDataUser;
var oTable;

/** Variable of tracking the IndexPK **/
var actionPK = undefined;
var action = undefined;

function $_init()
{
	window.onload = createUploader;
	$('#btnUsuarios').removeClass('btnMenu').addClass('btnMenuAct');
	
	var gaiSelected;
	
	$(document).ready(function() {
    	oTable = $('#dt_users').dataTable( {
					"bJQueryUI": true,
					"sPaginationType": "two_button",
					"bInfo": false,
					"bLengthChange": false,
					"bProcessing": true,
					"bServerSide": true,
					"sAjaxSource": actionForm + "?actionOfForm=search",
					"fnRowCallback": function( nRow, aData, iDisplayIndex ) {
						if ( jQuery.inArray(aData[0], gaiSelected) != -1 )
						{
					        $(nRow).addClass('row_selected');
						}
						return nRow;
					},
					"aoColumns": [
					  			null,
					  			null,
					  			null,
					  			null,
					  			null,
					  			null,
					  			null
					  		]

				});
    	
    	/* Click event handler */
    	$('#dt_users tbody tr').live('click', function () {
    		var aData = oTable.fnGetData(this);
    		var iId = aData[0];
    		actionPK = aData[0];
    		
    		gaiSelected =  [];
    		if ( $(this).hasClass('row_selected') ) {
	            $(this).removeClass('row_selected');
	            actionPK = undefined;
	        }
	        else {
	            oTable.$('tr.row_selected').removeClass('row_selected');
	            $(this).addClass('row_selected');
	            gaiSelected[gaiSelected.length++] = iId;
	        }
    	} );

	});
	
	$("#usersDialog").dialog({
		autoOpen:false, 
		height:600, 
		width:600, 
		dialogClass:'no-close',
		beforeClose: function() { $_ClearUsersPopForm(); },
		open: function() {
			$('#usersDialog').css('background','url(imagenes/fondo_texto.jpg)');
			$('#btnSave').click( function(e) {
				$('#usersPopForm').submit();
			});
		}
	});
	
	//Add Click for All Buttons in Search Form
	$("#btnAdd").click( function(e) {
		addProxyShow();
    });
	
	$('#btnEdit').click( function(e) {
		editProxyShow();
	});
	
	$('#btnErase').click( function(e) {
		delProxyShow();
	});
	
	$('#btnImport').click( function(e) {
		importProxyShow();
	});
}

function $_initPop()
{
	//Add Click for All Buttons in Pop Form
	$('#btnExit').click( function(e) {
		$('#usersDialog').dialog('close');
	});
	
	var idTypeUser;
	
	$_ValidatorSetDefaults();
	$_initPopValidator();
	
	//Populate User Data
	 $("#userId").removeAttr("disabled");
	if(action == iConst.EDIT)
	{
		$('#userId').val(joDataUser.userId);
		$('#userName').val(joDataUser.userName);
		$('#userPassword').val(joDataUser.userPassword);
		$('#userCompleteName').val(joDataUser.userCompleteName);
		$('#userEMail').val(joDataUser.userEMail);
		$('#userPhone').val(joDataUser.userPhone);
		$('#userAddress').val(joDataUser.userAddress);
		$('#userLocalidad').val(joDataUser.userLocalidad);
		idTypeUser = joDataUser.idTypeUser;
		$('#latDeg').val(joDataUser.latDeg);
		$('#latMin').val(joDataUser.latMin);
		$('#latSeg').val(joDataUser.latSeg);
		$('#lngDeg').val(joDataUser.lngDeg);
		$('#lngMin').val(joDataUser.lngMin);
		$('#lngSeg').val(joDataUser.lngSeg);
		
		$("#userId").attr("disabled", "disabled"); 
	}
	
	//Populate Combos
	$.ajax({ 
	    url: actionForm, 
	    type:'POST', 
	    data: 'actionOfForm=getTiposUsuario', 
	    dataType: 'json', 
	    success: function(json) { 
	        $.each(json, function(i, value) {
	        	if(value.idTypeUser == idTypeUser)
	        		$('#cmbTypeUser').append($('<option selected>').text(value.description).attr('value', value.idTypeUser));
	        	else
	        		$('#cmbTypeUser').append($('<option>').text(value.description).attr('value', value.idTypeUser));
	        });
	    }
	});
}

function addProxyShow()
{
	//Reset State of action and IndexPK
	actionPK = undefined;
	action = iConst.NEW;
	oTable.$('tr.row_selected').removeClass('row_selected');
	$('#usersDialog').load(popForm).dialog('open');
}

function editProxyShow()
{
	if(actionPK === undefined)
	{
		$_showMessage('ALERT', 'ALERTA', strMenssageSelectionUserInGrid);
		return;
	}
	
	action = iConst.EDIT;
	var paramData =  "actionOfForm=" + iConst.EDIT + "&idUser=" + actionPK;
	
    $.ajax({
        type: 'POST',
        url: actionForm,
        data: paramData,
		dataType: 'json',
        success: function(jsonObj)
                            {
        						joDataUser = jsonObj;
        						//Open Pop Dialog
        						$('#usersDialog').load(popForm).dialog('open');
                            }
        });
	
return true;
}

function $_saveUser(action)
{
	var paramData;
		
	if(action == iConst.EDIT) {
		paramData = 'actionOfForm=' + iConst.UPDATE + '&' + $("#usersPopForm").serialize() + '&idUser=' + actionPK;
	}
	else {
		paramData = 'actionOfForm=' + iConst.ADD + '&' + $("#usersPopForm").serialize();
		if($('#userId').val()!='')
			paramData += '&idUser=' + $('#userId').val();
	}
	
    $.ajax({
        type: 'POST',
        url: actionForm,
        data: paramData,
		dataType: 'json',
        success: function(jsonObj){
            if(jsonObj.status === 'OK'){
				$_showMessage('OK', jsonObj.status, jsonObj.msg);
				$('#usersDialog').dialog('close');
				oTable.fnReloadAjax();
			}
			else
				$_showMessage('ERR', jsonObj.status, jsonObj.msg);
        }
    });

return true;
}

function delProxyShow()
{
	if(actionPK === undefined)
	{
		$_showMessage('ALERT', 'ALERTA', strMenssageSelectionUserInGrid);
		return;
	}
	
	action = iConst.DELETE;
	
	$("#deleteUsersDialog").dialog({
		autoOpen: false, 
		width:350,
		position: 'center',
		open: function () {
			$('#deleteUsersDialog').css('background','url(imagenes/fondo_texto.jpg)');
			$('#btnConfirmDelete').click( function(e) {
				$_del();
			});
			$('#btnExitDelete').click( function(e) {
				$('#deleteUsersDialog').dialog('close');
			})
		}
	});
	$('#deleteUsersDialog').dialog('open');	
}

function $_del()
{
	var paramData = 'actionOfForm=' + action + '&idUser=' + actionPK;

    $.ajax({
            type: 'POST',
            url: actionForm,
            data: paramData,
			dataType: 'json',
            success: function(jsonObj)
                                {
                                    if(jsonObj.status === 'OK'){
										$_showMessage('OK', 'OK', jsonObj.msg);
										
										//Reset State of action and IndexPK
										actionPK = undefined;
										action = iConst.NEW;
										oTable.fnReloadAjax();
									}
									else
										$_showMessage('ERR', 'ERROR', jsonObj.msg);
                                    $('#deleteUsersDialog').dialog('close');
                                }
            });

return true;
}

function importProxyShow()
{
	$("#uploadUsersDialog").dialog({
		autoOpen: false, 
		width:350,
		position: 'center',
		modal: true,
		open: function () {
			$('#uploadUsersDialog').css('background','url(imagenes/fondo_texto.jpg)');
		}
	});
	$('#uploadUsersDialog').dialog('open');
}

function createUploader(){            
    var uploader = new qq.FileUploader({
        element: document.getElementById('fileUpload'),
        action: 'uploadFiles.php',
        onComplete: function(id, fileName, responseJSON){
        	if(responseJSON.success)
    		{
        		$.ajax({
                    type: 'POST',
                    url: actionForm,
                    data: 'actionOfForm=' + iConst.UPLOAD + '&' + 'fileName=' + fileName,
        			dataType: 'json',
                    success: function(jsonObj)
                                        {
                                            if(jsonObj.status === 'OK')
        										$_showMessage('OK', 'OK', jsonObj.msg);
        									else
        										$_showMessage('ERR', 'ERROR', jsonObj.msg);
    										oTable.fnReloadAjax();
                                        }
                    });
    		}
        	else
        		$_showMessage('ERR', 'ERROR', responseJSON.error);
        },
    });
}

function $_initPopValidator()
{
	$('#usersPopForm').validate({
		submitHandler: function() {
			$_saveUser(action);
		}, 		
		rules: {
			userName: {required: true,minlength: 1},
			userPassword: {required: true,minlength: 1},
			userCompleteName: {required: true,minlength: 1},
			latitude: {required: true,minlength: 1},
			longitude: {required: true,minlength: 1},
			cmbTypeUser: {required: true,minlength: 1}
		},
		messages: {
			userName: {required: '',minlength: ''},
			userPassword: {required: '',minlength: ''},
			userCompleteName: {required: '',minlength: ''},
			latitude: {required: '',minlength: ''},
			longitude: {required: '',minlength: ''},
			cmbTypeUser: {required: '',minlength: ''}
		}
	});
}

function $_ClearUsersPopForm()
{	
	$("#usersDialog").empty();
}